import logging

from coin.base.datetime_util import to_datetime
from coin.base.timestamp import get_timestamp
from coin.exchange.base.order_gateway import OrderSide
from coin.exchange.huobi_futures.kr_rest.native_private_client import HuobiFuturesOrderSide
from coin.exchange.okex_futures.types import OkexFuturesOrderSide
from coin.strategy.mm.base.dump.pass_unhedge import FillRow
from coin.strategy.mm.feed import SubscriptionRequest


def _convert_exchange(subreq):
  if subreq.market_type == 'Futures' and subreq.exchange == 'Huobi':
    exchange = 'HuobiFutures'
  elif subreq.market_type == 'Futures' and subreq.exchange == 'Okex':
    exchange = 'OkexFutures'
  else:
    exchange = subreq.exchange
  return exchange


class FillLogDumper(object):
  def __init__(self, subreq):
    assert isinstance(subreq, SubscriptionRequest)
    self._subreq = subreq
    self._logger = logging.getLogger('FillLogDumper')

  def _get_order_side_universe(self):
    subreq = self._subreq
    if subreq.market_type == 'Futures' and subreq.exchange == 'Huobi':
      buy_order_side = [HuobiFuturesOrderSide.BUY_OPEN, HuobiFuturesOrderSide.BUY_CLOSE]
      sell_order_side = [HuobiFuturesOrderSide.SELL_OPEN, HuobiFuturesOrderSide.SELL_CLOSE]
    elif subreq.market_type == 'Futures' and subreq.exchange == 'Okex':
      buy_order_side = [OkexFuturesOrderSide.BUY_OPEN, OkexFuturesOrderSide.BUY_CLOSE]
      sell_order_side = [OkexFuturesOrderSide.SELL_OPEN, OkexFuturesOrderSide.SELL_CLOSE]
    else:
      buy_order_side = [OrderSide.BUY]
      sell_order_side = [OrderSide.SELL]
    return buy_order_side, sell_order_side

  def dump_fill(self, fill_price, fill_qty, order):
    timestamp = get_timestamp()

    order_side = order.order_side
    buy_order_side, sell_order_side = self._get_order_side_universe()
    if order_side in buy_order_side:
      side_sign = 1
    elif order_side in sell_order_side:
      side_sign = -1
    else:
      raise ValueError('Invalid order side: %s' % order_side)

    row = FillRow(time=timestamp,
                  time_hr=to_datetime(timestamp),
                  exchange=_convert_exchange(self._subreq),
                  product=order.product.symbol,
                  side=side_sign,
                  price=fill_price,
                  qty=fill_qty,
                  maker=-1,
                  fee=0,
                  pos=0,
                  balance=0)
    self._logger.info(row.to_log_string())
